package com.wang.madness.handler;

import com.wang.madness.customEnum.ResultCode;
import com.wang.madness.customResponse.ErrorResult;
import com.wang.madness.exception.ApiRuntimeException;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理类
 *
 * @author A
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

  /**
   * 自定义异常处理
   * @param apiRuntimeException 自定义异常
   * @return  错误的请求
   */
  @ExceptionHandler(ApiRuntimeException.class)
  public ResponseEntity<ErrorResult<String>> apiRuntimeExceptionHandler (ApiRuntimeException apiRuntimeException) {
    int exceptionCode = apiRuntimeException.getCode();
    String data = apiRuntimeException.getMsg();
    ResultCode[] resultCodes = ResultCode.values();
    String exceptionMsg = data;
    for (ResultCode resultCode : resultCodes) {
      if (resultCode.getCode() == exceptionCode) {
        exceptionMsg = resultCode.getMsg();
      }
    }
    return new ResponseEntity<>( new ErrorResult<>(exceptionCode, exceptionMsg, data), HttpStatus.BAD_REQUEST);
  }

  @ExceptionHandler(Exception.class)
  public ResponseEntity<ErrorResult<Object>> exceptionHandler (Exception exception) {
    log.error(exception.getMessage());
    return new ResponseEntity<>(new ErrorResult<>(ResultCode.SERVER_ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
  }

  /**
   * 接口参数校验自动抛异常
   *
   * @param methodArgumentNotValidException 参数校验异常
   * @return 结果信息
   */
  @ExceptionHandler(MethodArgumentNotValidException.class)
  public ResponseEntity<ErrorResult<String>> methodArgumentNotValidExceptionHandler(
      MethodArgumentNotValidException methodArgumentNotValidException) {
    StringBuilder stringBuilder = new StringBuilder();
    //从异常对象中拿到ObjectError对象
    List<ObjectError> allErrors = methodArgumentNotValidException.getBindingResult()
        .getAllErrors();
    //然后提取错误提示信息进行返回
    allErrors.forEach(error -> {
      stringBuilder.append(error.getDefaultMessage());
      if ((allErrors.indexOf(error) != (allErrors.size() - 1))) {
        stringBuilder.append(",");
      }
    });
    String result = stringBuilder.toString();
    return new ResponseEntity<>(new ErrorResult<>(ResultCode.VALIDATE_FAILED, result), HttpStatus.BAD_REQUEST);
  }

}
